<?php
session_start();
if ( $_SESSION['estado'] == "teacher_login" ) {
//include the header
include("header.php");
//if the session group isn't empty, it will run the code
if (!empty($_SESSION['group'])) {

?>

<h1>Import Students</h1>

<br />
<form action="importstudents.php" method="post">
Insert a list of students : <br /><br />
For example: <b>Username;First_Surname;Second_Surname;Name;Email</b>
<br /><br />
<textarea id="TextArea1" name="texto" cols="100" rows="10"></textarea><br />
<br />
<input type="submit" value="Import students" />
</form>
<br />

<br />

 <?php 
//it runs after pressing the submit button
if ($_SERVER['REQUEST_METHOD']=='POST') {
	//this function have the settings for conect to the database
	require("mysqlsettings.php");

	//this function sets the connection with the database
	$dbc = mysql_connect($server, $username, $password);
	mysql_set_charset('utf8',$dbc);
	mysql_select_db('my_marks', $dbc);
	

	//if the textbox not empty, run the code
	if (!empty($_POST['texto'])) {
		
		//the variables take the list of students
		$type = "Student";
		$text = $_POST['texto'];
		$text = htmlentities($text);
		$linia = explode("\n",$text);
		$contador = count($linia);
		$group = $_SESSION['group'];
		
		
			//we start a loop to travel the array '$linia'
			for ($i=0; $i < $contador; $i++) {
			
					//we separate the line of text in an array of words
					$palabra = explode(";",$linia[$i]);
					$length_palabra = count($palabra);

						//if the length of the array doesn't match with the values that the user should have entered
						if ($length_palabra != 5)
						{
							$execute_import = false;
						}
						
						else 
						{
						
							//start another loop to travel the array '$palabra'
							for ($j=0; $j < $length_palabra; $j++ ) {
								
								//check if the value of the array is not empty or isn't a carriage return
								if ($palabra[$j] != "" && $palabra[$j] != "\r")
								{
									$execute_import = true;
								}
								
								else 
								{
									$execute_import = false;
									break;
								}
						
							}
							
						}
						
					//if the values entered are correct, we execute the import of the student
					if ($execute_import == true) 
					{	
					
						//check if there is a user in the database with the same username as the one entered
						//by doing this we detect this error before starting the insert 
						
						$usern = mysql_real_escape_string($palabra[0]); //make the username safe to use in the query
						$query = "SELECT Username FROM users WHERE Username = '$usern'";
						$r = mysql_query($query, $dbc); //Run the query
						$r2 = mysql_num_rows($r); //return the number of rows retrieved by the previous SELECT
							
							
						//if the SELECT has a result, there is a user with the same username entered
						//if the SELECT hasn't retrieved a result, there isn't a user in the database with the username entered
							
							if ($r2 > 0)
							{
								echo "Username entered is already in use. Try with a different username.";
								echo "<br>";
							}
							else {
							
						//we assign a random number for use it as the password of the users
						$numero_aleatorio = rand(1,10000);
						//we create the message that is sent to the students after being registered
						$message = "Welcome to Sjo_My_Marks. Your username is ". $palabra[0] ." and your password is ". $numero_aleatorio .".";
						$array_password[$i] = $numero_aleatorio;
						$array_palabra[$i] = $palabra[0];
						//we convert the password at md5 to be insert at the database
						$password = md5($numero_aleatorio);
						//define the query
						$query = "INSERT INTO `my_marks`.`users` (`ID`, `Username`, `First_Surname`, `Second_Surname`, `Name`, `Type`, `Password`, `Group`,`Email`) VALUES (NULL, '".$palabra[0]."', '".$palabra[1]."', '".$palabra[2]."', '".$palabra[3]."', '".$type."', '".$password."', '".$group."','".$palabra[4]."');";
						//if the query runs ok,we will sent the message to the students and print a message
						if (@mysql_query($query, $dbc)) {
						mail($palabra[4], 'Welcome to Sjo_My_Marks!', $message);
						print '<p>The user <b>'. $array_palabra[$i] .'</b> has been added with the password <b>'.$array_password[$i].'</b>.</p>';
						} else {
						//if the query doesn't run ok, we will print an error message
						print '<p style="color: red;">Could not run the query because:<br />' . mysql_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
						}
						
						}
							//Optional, but we ensure to free up the memory used by the query 
							mysql_free_result ($r);
					}
					
					else 
					{	
						//if the insert is not correct, we will print an error message
						echo "You must insert the list of students as the example.";
						echo "<br>";
					}

			}

	}
	//if the textbox is empty, we will print an error message 
	else {
	
	echo 'You must fill the field!';
	
	}

}

}

else {
	//if the session group is empty, we will print an error message 
	echo "<p style='color: red;'>Please, choose a group before continuing.</p>";
	echo "<br /><a href='ChooseGroup.php'>Return to Choose Group</a><br /><br />";	
	
}
	
}
//we check if the session 'estado' is a student
else if ( $_SESSION['estado'] == "student_login" ) {
//include header
include("headerstudent.php");

}
//if you don't have a session started, you can't enter at this page
else {
include("noacces.php");

}
//include footer
include("footer.php");



?>
